package com.portal.listener;

import com.portal.constant.MQConst;
import com.portal.model.vo.CartVo;
import com.portal.service.CartService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class ClearCartListener {

    @Autowired
    private CartService cartService;

    @RabbitListener(queues = MQConst.CLEAR_CART_QUEUE)
    public void clearCart(CartVo cartVo, Channel channel, Message message) throws IOException {
        log.info("监听器清空购物车, 购物车对象：{}", cartVo);

        //channel.basicAck();  手动确认
        //channel.basicNack();  重投
        //channel.basicReject(); 拒绝

        // 获取消息id
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            // 清空购物车
            cartService.clearCart(cartVo.getUserId());
            // 消费者消费消息，手动应答
            channel.basicAck(deliveryTag,false);
        } catch (IOException e) {
            e.printStackTrace();
            // 是否重投标记
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            if (!redelivered) {
                // 重投
                channel.basicNack(deliveryTag,false,true);
            } else {
                // 拒绝
                channel.basicReject(deliveryTag,false);
            }
        }
    }
}














